package com.jike.noobmoney.mvp.view.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jike.noobmoney.R;
import com.jike.noobmoney.adapter.TaskDetailUserAdapter;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.MyPushDetailEntity;
import com.jike.noobmoney.helper.ImageLoader;
import com.jike.noobmoney.mvp.presenter.TaskPresenter;
import com.jike.noobmoney.net.IView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPreview;

public class UserTaskDetailActivity extends BaseActivity implements IView {

    public static final String t_id = "t_id";

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_task_number)
    TextView tvTaskNumber;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_taskname)
    TextView tvTaskname;
    @BindView(R.id.tv_tasktime)
    TextView tvTasktime;
    @BindView(R.id.tv_lastnumber)
    TextView tvLastnumber;
    @BindView(R.id.tv_text)
    TextView tvText;
    @BindView(R.id.ll_image)
    LinearLayout llImage;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.tv_type_title)
    TextView tvTypeTitle;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.iv_ecode)
    ImageView ivEcode;
    @BindView(R.id.tv_http)
    TextView tvHttp;
    private String taskId;
    private TaskPresenter taskPresenter;

    private TaskDetailUserAdapter adapter;
    private List<MyPushDetailEntity.TaskstepBean> mData = new ArrayList<>();

    @Override
    protected int layoutResID() {
        return R.layout.activity_usertask_detail;
    }

    @Override
    protected void initData() {
        if (getIntent() != null) {
            taskId = getIntent().getStringExtra(UserTaskDetailActivity.t_id);
        }
        tvTitle.setText("发布任务详情");
        taskPresenter = new TaskPresenter(this);

        //adapter
        adapter = new TaskDetailUserAdapter(context);
        //manager
        recyclerview.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerview.setAdapter(adapter);

        getData();
    }

    /**
     * 如果要全屏,重写这个方法返回false
     */
    public Boolean isfits() {
        return true;
    }

    /**
     * 如果要白色主题,重写这个方法返回false
     */
    public boolean ismain() {
        return true;
    }
    /**
     * 获取任务详情
     */
    private void getData() {
        showProgress();
        taskPresenter.getMyPushDetail(taskId, ConstantValue.RequestKey.my_push_detail);
    }

    private void addImg(String url) {
        ImageView newImg = new ImageView(this);
        //设置想要的图片，相当于android:src="@drawable/image"
        //newImg.setImageResource(R.mipmap.ic_launcher);
        ImageLoader.displayImage(this, url, newImg);

        //设置子控件在父容器中的位置布局，wrap_content,match_parent
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        // 也可以自己想要的宽度，参数（int width, int height）均表示px
        // 如dp单位，首先获取屏幕的分辨率在求出密度，根据屏幕ppi=160时，1px=1dp
        //则公式为 dp * ppi / 160 = px ——> dp * dendity = px
        //如设置为48dp：1、获取屏幕的分辨率 2、求出density 3、设置
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        float density = displayMetrics.density;
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
                (int) (48 * density),
                (int) (48 * density));
        //相当于android:layout_marginLeft="8dp"
        params.leftMargin = 20;
        params.rightMargin = 20;
        params.topMargin = 20;
        //addView(View child)，默认往已有的view后面添加，后插入，不设置布局params,默认wrap_content
        //llImage.addView(newImg);
        //addView(View child, LayoutParams params)，往已有的view后面添加，后插入,并设置布局
        llImage.addView(newImg, params);
    }

    @OnClick({R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        dismissProgress();
        if (ConstantValue.RequestKey.my_push_detail.equals(actionType)) {
            MyPushDetailEntity data1 = (MyPushDetailEntity) data;
            List<MyPushDetailEntity.TaskinfoBean> taskinfoBeans = data1.getTaskinfo();
            List<MyPushDetailEntity.TaskstepBean> taskstep = data1.getTaskstep();
            if (taskinfoBeans != null && taskinfoBeans.size() > 0) {
                MyPushDetailEntity.TaskinfoBean item = taskinfoBeans.get(0);

                //任务id
                tvTaskNumber.setText(item.getTasknum());
                //任务总钱
                tvTotalMoney.setText("" + item.getTotalmoney());
                //任务名称
                tvTaskname.setText("任务名称:" + (TextUtils.isEmpty(item.getTaskname()) ? "小白任务" : item.getTaskname()));
                //发布时间
                tvTasktime.setText("发布时间:" + item.getCreatetime());
                //总量
                //tvNumber.setText("总量:" + item.getNumber());
                //为完成量
                tvLastnumber.setText("未完成:" + item.getLastnumber());

                //任务内容
                tvText.setText(item.getText());
                //任务图片
//                List<MyPushDetailEntity.TaskinfoBean.ImageBean> image = item.getImage();
//                if (image != null && image.size() > 0) {
//                    for (int i = 0; i < image.size(); i++) {
//                        MyPushDetailEntity.TaskinfoBean.ImageBean imageBean = image.get(i);
//                        String img = imageBean.getImg();
//                        String url = ConstantValue.IMG_BASEURL + img;
//                        addImg(url);
//                    }
//                }

                int opentype = item.getOpentype(); //1二维码  2链接
                String openurl = item.getOpenurl();
                if (opentype == 1) {
                    tvType.setText("二维码");
                    ivEcode.setVisibility(View.VISIBLE);
                    tvHttp.setVisibility(View.GONE);
                    Glide.with(this).load(ConstantValue.IMG_BASEURL + openurl).into(ivEcode);
                } else if (opentype == 2) {
                    tvType.setText("链接");
                    ivEcode.setVisibility(View.GONE);
                    tvHttp.setVisibility(View.VISIBLE);
                    tvHttp.setText(openurl);
                } else {
                    tvTypeTitle.setVisibility(View.GONE);
                    tvType.setVisibility(View.GONE);
                    ivEcode.setVisibility(View.GONE);
                    tvHttp.setVisibility(View.GONE);
                }

                ivEcode.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ArrayList<String> photoPaths = new ArrayList<>();
                        photoPaths.add(ConstantValue.IMG_BASEURL + openurl);
                        PhotoPreview.builder()
                                .setPhotos(photoPaths)
                                .setCurrentItem(0)
                                .setShowDeleteButton(true)
                                .start((Activity) context);
                    }
                });
            }

            if (taskstep != null && taskstep.size() > 0) {
                mData.clear();
                mData.addAll(taskstep);
            }
            adapter.refresh(mData);
        }
    }

    @Override
    public void onFailed(String code, String msg) {
        dismissProgress();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
